# -*- coding: utf-8 -*-

# --------------------------------------------------------------------------
#
# Search modules as subfunctions of the class Tab
#
# --------------------------------------------------------------------------

import re
import urllib2
import urlparse

class Tab(object):
	
	def search_tab(self, artist, title):
		""" Searches for tabs by self.artist and self.title
		"""
		self.artist = artist
		self.title = title
		
		return self.ultimate_guitar_com() or self.etabs_org() or self.cifras_com_br()


	def _fetch_url_content(self, someurl):
		""" Gets webpage and returns its content.
		"""
		try:
			resp = urllib2.urlopen(someurl)
			html = resp.read()
			return html
		except urllib2.HTTPError, e:
			if e.code != 404 or __debug__:
				print "There was a problem opening url <%s>: (%s) %s" % (someurl, e.code, e)			
		except urllib2.URLError, e:
			print "There was a problem opening url <%s>: %s" % (someurl, e.reason)			
		except Exception, e:
			print "There was a problem opening url <%s>: %s" % (someurl, e)
		
	

	def _fetch_tab(self, site_url, tab_re, print_re=None):
		""" Method that searches for tabs in a website
		    @param site_url: url of the tab with artist and title
		    @param tab_re: regular expresion (str) to fetch tabs
		    @param print_re: regular expresion (str) to tech url to printed version
		    @return str
		"""

		if __debug__:
			print "Artist %s | Title %s " % (self.artist, self.title)

		if __debug__:
			print "Fetching from: ", site_url
			
		## getting tab page
		all_html = self._fetch_url_content(site_url)
		if all_html:			
			## getting print version
			if print_re:
				print_re = re.compile(print_re)
				print_match = re.search(print_re, all_html)
				
				url_host = urlparse.urlparse(site_url)				
				all_html = self._fetch_url_content("%s://%s/%s" % (url_host[0], url_host[1], print_match.group(1)))
			
			tab_re = re.compile(tab_re, re.DOTALL)
			tab_match = re.search(tab_re, all_html)
			if tab_match and not tab_match.group(1).startswith("THIS TAB IS NOT AVAILABLE"):
				tab = tab_match.group(1)				
				return self._strip_tags(tab)
		return ""
	
			
	def _strip_tags(self, value):
		""" Removes all html tags from value.
		"""
		return re.sub(r'<[^>]*?>', '', value)


	def ultimate_guitar_com(self):
		""" Searches for a tab: ultimate-guitar.com
		"""
		artist_url = self.artist.replace(" ", "_").lower()
		title_url = self.title.replace(" ", "_").lower()

		url_crd = 'http://www.ultimate-guitar.com/tabs/%s/%s/%s_crd.htm' % (artist_url[0], artist_url, title_url)
		url_tab = 'http://www.ultimate-guitar.com/tabs/%s/%s/%s_tab.htm' % (artist_url[0], artist_url, title_url)
		print_re = '<a href=\"(.+?)\"(.+?)>Print this tab</a>'
		tab_re = '<pre>(.+?)</pre>'

		return self._fetch_tab(url_crd, tab_re, print_re) or self._fetch_tab(url_tab, tab_re, print_re)


	def etabs_org(self):
		""" Searches for a tab: e-tabs
		"""
		artist_url = self.artist.replace(" ", "_").lower()
		title_url = self.title.replace(" ", "_").lower()
		
		url_tab = 'http://www.e-tabs.org/tab/%s/%s' % (artist_url, title_url)
		tab_re = '<pre>(.+?)</pre>'
			
		return self._fetch_tab(url_tab, tab_re)


	def cifras_com_br(self):
		""" Searches for a tab: cifras.com.br
		"""
		artist_url = self.artist.replace(" ", "-").lower()
		title_url = self.title.replace(" ", "-").lower()

		url_tab = 'http://www.cifras.com.br/cifra/%s/%s/0,,imprimir' % (artist_url, title_url)
		tab_re = '<span id="spCifra"><pre><div style="margin-left:20px"> (.+?)<font class="vis">veja esta cifra correta em'
			
		return self._fetch_tab(url_tab, tab_re)


if __name__ == '__main__':
	## Silly tests... maybe one day adding some unit tests might be a good idea :)
	tab = Tab()
		
	correct_urls = ("http://www.e-tabs.org/tab/beach_boys/in_my_room_(2)", )
	error_urls = ("http://www.e-tabs.org/tab/beach_oys/in_my_room_(2)", "abc", "", "http://umaurlqqqnaoexisteenuncavaiexistir.com.bla")
	for item in correct_urls:
		print tab._fetch_url_content(item)
		
	for item in error_urls:
		print tab._fetch_url_content(item)

	print tab.search_tab("Camera Obscura", "swimming pool")
	
	print tab.search_tab( "coldplay", "careful where you stand")
			
	assert tab.search_tab("Chico burque", "a banda") is ""
	
	print tab.search_tab("Chico buarque", "a banda")
	
	print "Done."